package cn.laike.modules.dev.controller.api;


import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import cn.laike.common.utils.R;
import cn.laike.common.utils.SendSms;
import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.entity.MemberEntity;
import cn.laike.modules.dev.entity.MobileMessageRecorderEntity;
import cn.laike.modules.dev.entity.MobileMessageTemplateEntity;
import cn.laike.modules.dev.service.MemberService;
import cn.laike.modules.dev.service.MobileMessageRecorderService;
import cn.laike.modules.dev.service.MobileMessageTemplateService;
import cn.laike.modules.dev.utils.DevCacheUtils;
import cn.laike.modules.dev.utils.DevUtils;


/**
 * 酒店预订 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/api/member")
public class ApiMemberController {

	@Autowired
	private MemberService memberService;
	@Autowired
	private MobileMessageTemplateService mobileMessageTemplateService;
	@Autowired
	private MobileMessageRecorderService mobileMessageRecorderService;
	
	
	
	
	/**
	 * 获取小程序openid
	 *  http://localhost/api/member/get_open_id?uid=1&code=111
	 * @param uid
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "get_open_id")
    public R get_open_id(@RequestParam(value="uid",defaultValue="0")Long uid,
    		@RequestParam(value="code",defaultValue="")String code) {
        return DevUtils.wxlogin(uid, code);
    }
	
	/**
	 * http://localhost/api/member/get_member?openid=oTa4I0eOj638wk74MDv3S3zPKWnU
	 * @param openid
	 * @return
	 */
	@RequestMapping(value="get_member")	
	public R get_member(@RequestParam(value="openid",defaultValue="")String openid){
		try {
			MemberEntity member = memberService.getMemberByOpenid(openid);
        	if(member != null && member.getId() != null && member.getId() > 0){
        		return R.ok().put("member", member);
        	}else{
				return R.error(10000, "请注册");
        	}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("参数异常!");
		}
	} 
	
	/**
	 * 发送短信验证码
	 * http://localhost/admin/api/member/send_mobile_code?tid=1&15830769707=111
	 * @param tid
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="send_mobile_code")	
	public R sendMobileCode(@RequestParam(value="uid",defaultValue="0")Long uid,@RequestParam(value="tid",defaultValue="0")Long tid,
    		@RequestParam(value="mobile",defaultValue="")String mobile){
		try {
			if(StringUtils.isNotEmpty(mobile)){
				MobileMessageTemplateEntity template = mobileMessageTemplateService.selectById(tid);
				if(template != null && template.getId() != null && template.getId() > 0){
					MemberEntity isMember = memberService.getMemberByMobile(uid, mobile);
					if(isMember != null && isMember.getId() != null && isMember.getId() > 0){
		        		return R.error("该手机号已注册！");
		        	}else{
		        		ConfigEntity config = DevCacheUtils.getConfig(template.getUid());
	    				//生成随机码
	    				String code=SendSms.getRandomCode(4);
	    		        SendSmsResponse smsresponse = SendSms.sendSms(config.getAccessKeyId(),config.getAccessKeySecret(), template.getSign(), template.getCode(),mobile, code);
	    			  
	    				MobileMessageRecorderEntity recorder = new MobileMessageRecorderEntity();
	    				recorder.setUid(uid);
	    				recorder.setMobileMessageTemplateId(template.getId());
	    				recorder.setMobileMessageTemplateName(template.getName());
	    				recorder.setMobile(mobile);
	    				recorder.setVerificationCode(code);
	    				recorder.setCreateTime(new Date());
	    				if("OK".equals(smsresponse.getCode())){
	    					recorder.setReturnCode("OK");
	    					recorder.setReturnMessage(smsresponse.getMessage());
	    					mobileMessageRecorderService.insert(recorder);
	    					return R.ok("验证码发送成功!");
	    				}else{
	    					recorder.setReturnCode(smsresponse.getCode());
	    					recorder.setReturnMessage(smsresponse.getMessage());
	    					mobileMessageRecorderService.insert(recorder);
	    					return R.error(smsresponse.getMessage());
	    				}
		        	}
				}else{
		        	return R.error("短信模板ID不存在！");
				}
			}else{
				return R.error("请输入手机号");
			}
    		
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("参数异常!");
		}
	} 
 	
	/**
	 * 登陆/注册 小程序会员
	 * http://localhost/admin/api/member/create_member?openid=1
	 * @param request
	 * @param response
	 */
	@PostMapping(value = "create_member")
	public R create_member(MemberEntity member,@RequestParam(value="code",defaultValue="")String code) {
		try {
			if(StringUtils.isNotEmpty(member.getOpenid())){
				MemberEntity isMember = memberService.getMemberByOpenid(member.getOpenid());
	        	if(isMember != null && isMember.getId() != null && isMember.getId() > 0){
	        		return R.error("该用户已注册！");
	        	}else{
	        		if(code != null && code.equals("ME7056607")) {	//微信一键授权
	        			member.setCreateTime(new Date());
    	    			member.setName(member.getNickname());
    	    			member.setMoney(0d);
    	        		memberService.insert(member);
    	        		// 生成会员卡号
    	        		member.setNumber(""+ StringUtils.leftPad("" + member.getId(), 5, "0")); // 会员卡号
    	        		memberService.insertOrUpdate(member);
    	        		DevCacheUtils.del("dev_member_"+member.getOpenid());
    	        		return R.ok("注册成功！").put("member", member);
	        		}else {
	        			//验证新手机号 的 验证码
	    				MobileMessageRecorderEntity mobileMessageRecorder = mobileMessageRecorderService.getByMobileAndCode(member.getMobile(), code);
	    				if(mobileMessageRecorder==null){
	    					return R.error("验证码错误！");
	    				}else if((System.currentTimeMillis() - mobileMessageRecorder.getCreateTime().getTime()) > 1000*60*10){
	    					return R.error("验证码已过期，请重新获取！");
	    				}else{
	    					member.setCreateTime(new Date());
	    	    			member.setName(member.getNickname());
	    	    			member.setMoney(0d);
	    	    			member.setRecommendMoney(0d);
	    	        		memberService.insert(member);
	    	        		// 生成会员卡号
	    	        		member.setNumber(""+ StringUtils.leftPad("" + member.getId(), 5, "0")); // 会员卡号
	    	        		memberService.insertOrUpdate(member);
	    	        		DevCacheUtils.del("dev_member_"+member.getOpenid());
	    	        		return R.ok("注册成功！").put("member", member);
	    				}
	        			
	        		}
    				
	        	}
    		}else{
    			return R.error("注册失败，参数异常!");
    		}
			
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("参数异常!");
		}
	}
	
	/**
	 * 完善信息
	 * http://localhost/admin/api/member/perfect_info?openid=1
	 * @param member
	 * @param code
	 * @return
	 */
	@PostMapping(value = "perfect_info")
	public R perfect_info(MemberEntity member) {
		if(StringUtils.isNotEmpty(member.getOpenid())){
			MemberEntity isMember = memberService.getMemberByOpenid(member.getOpenid());
        	if(isMember != null && isMember.getId() != null && isMember.getId() > 0){
        		isMember.setName(member.getName());
        		memberService.insertOrUpdate(isMember);
        		return R.ok("完善信息成功！");
        	}else{
        		return R.error("用户不存在");
        	}
		}else{
			return R.error("参数异常!");
		}
	}
	
	/**
	 * http://localhost/admin/api/member/get_phone_number?uid=1&code=&encryptedData=&iv=
	 * @param encryptedData
	 * @param uid
	 * @param code
	 * @param iv
	 * @return
	 */
	@RequestMapping(value = "get_phone_number")
	public Object get_phone_number(Long uid,String code, String encryptedData, String iv) {
        //HttpUtil.getOpenid这个方法是我自己封装的方法，传入code后然后获取openid和session_key的，把他们封装到json里面
		String session_key = DevUtils.getSessionKey(uid,code);
		
			 // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(session_key);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
		return null;
	}

 	
	
}
